package com.elric.mall.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.elric.mall.mapper.BaseUpperUnitMapper;
import com.elric.mall.mapper.ProjectEntityNewDao;
import com.elric.mall.model.BaseUpperUnit;
import com.elric.mall.model.ProjectEntityNew;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 实现功能：
 *
 * @author 作者[Yuxuan.he]
 * @version 1.0.00  2021-09-08 12:05
 */
@Service
public class SettingService {

    @Autowired
    private ProjectEntityNewDao projectEntityNewDao;

    @Autowired
    private BaseUpperUnitMapper baseUpperUnitMapper;

    public void insertProjectInfo(ProjectEntityNew projectEntityNew) {
        projectEntityNew.setId(UUID.randomUUID().toString());
        projectEntityNew.setCreateId(UUID.randomUUID().toString());
        projectEntityNew.setCreateTime(new Date());
        projectEntityNew.setUpdateTime(new Date());
        projectEntityNewDao.insertBase(projectEntityNew);
        projectEntityNewDao.insertExtend(projectEntityNew);
    }

    @Transactional(rollbackFor = Exception.class)
    public void init() {
        // 初始化基础字典表数据
        projectEntityNewDao.deleteBaseInfo();
        projectEntityNewDao.initBaseInfo();
        // 初始化能力体系数据
        projectEntityNewDao.deleteNltx();
        projectEntityNewDao.initNltx();
        // 初始化行政区划数据
        projectEntityNewDao.deletePrevinces();
        projectEntityNewDao.initPrevinces();
        // 初始化项目信息数据
        projectEntityNewDao.deleteProjectInfo();
        projectEntityNewDao.initProjectInfo();
        projectEntityNewDao.deleteExtendInfo();
        projectEntityNewDao.initExtendInfo();

        // 初始化大单位数据
        baseUpperUnitMapper.deleteUpperUnit();
        List<BaseUpperUnit> list = baseUpperUnitMapper.selectAllZGUnit();
        if (CollectionUtil.isNotEmpty(list)) {
            baseUpperUnitMapper.insertBatch(list);
        }

        // 初始化作战体系数据
        projectEntityNewDao.deleteZztx();
        projectEntityNewDao.initZztx();

        // 初始化数据包相关数据
        projectEntityNewDao.deleteZzjg();
        projectEntityNewDao.initZzjg();

        projectEntityNewDao.deleteImplementation();
        projectEntityNewDao.initImplementation();

        projectEntityNewDao.deleteProjectpszz();
        projectEntityNewDao.initProjectpszz();

        projectEntityNewDao.deleteBasembtx();
        projectEntityNewDao.initBasembtx();

        projectEntityNewDao.deleteResourceProtection();
        projectEntityNewDao.initResourceProtection();

        projectEntityNewDao.deleteBaseSsly();
        projectEntityNewDao.initBaseSsly();

        projectEntityNewDao.deleteFundingInvestment();
        projectEntityNewDao.initFundingInvestment();

        projectEntityNewDao.deleteLeadDoor();
        projectEntityNewDao.initLeadDoor();

        projectEntityNewDao.deleteBranchContact();
        projectEntityNewDao.initBranchContact();

        projectEntityNewDao.deleteGhjzdspqx();
        projectEntityNewDao.initGhjzdspqx();

        projectEntityNewDao.deleteBaseJfqd();
        projectEntityNewDao.initBaseJfqd();

        projectEntityNewDao.deleteBaseSsgh();
        projectEntityNewDao.initBaseSsgh();

        projectEntityNewDao.deleteBaseZzjg();
        projectEntityNewDao.initBaseZzjg();

        projectEntityNewDao.deleteConstructionPeriod();
        projectEntityNewDao.initConstructionPeriod();

        projectEntityNewDao.deleteTextConstruction();
        projectEntityNewDao.initTextConstruction();

        projectEntityNewDao.deleteLhjszb();
        projectEntityNewDao.initLhjszb();

        projectEntityNewDao.deleteTextSort();
        projectEntityNewDao.initTextSort();

        projectEntityNewDao.deleteUploadAnnex();
        projectEntityNewDao.initUploadAnnex();
    }

    public void formatRange(ProjectEntityNew p) {
        // 如果建设周期不为空
        if (!Objects.isNull(p.getJszq())) {
            String[] rangs = p.getJszq().split("-");
            // 如果周期包含"-"，则说明起止日期为2020.01-2021.01格式
            if (rangs.length >= 2){
                // 处理起始日期
                String[] startStrs = rangs[0].split("\\.");
                // 如果包含"."，说明是2020.01格式
                if (startStrs.length >= 2) {
                    p.setProjectStartYear(startStrs[0]);
                    p.setProjectStartMonth(startStrs[1]);
                } else {
                    // 如果不包含，直接默认当年一月
                    p.setProjectStartYear(startStrs[0]);
                    p.setProjectStartMonth("01");
                }

                // 处理截止日期
                String[] endStrs = rangs[1].split("\\.");
                // 如果包含"."，说明是2020.01格式
                if (startStrs.length >= 2) {
                    p.setProjectEndYear(endStrs[0]);
                    p.setProjectEndMonth(endStrs[1]);
                } else {
                    // 如果不包含，直接默认当年一月
                    p.setProjectEndYear(endStrs[0]);
                    p.setProjectEndMonth("01");
                }

            } else {
                // 如果没有用"-"分割开，说明直接存的周期（月），需要先取开始日期进行计算
                String year = p.getProjectStartYear();
                String month = p.getProjectStartMonth();
                if (!Objects.isNull(year)&&!Objects.isNull(month)){
                    DateFormat format = new SimpleDateFormat("yyyyMM月");
                    try {
                        Date start = format.parse(year + "" + month);
                        if (!Objects.isNull(p.getJszq())) {
                            Integer months = Integer.parseInt(p.getJszq());
                            Calendar cal = Calendar.getInstance();
                            // 格式化起始月数据
                            p.setProjectStartMonth(cal.get(Calendar.MONTH) + "");
                            cal.setTime(start);
                            cal.add(Calendar.MONTH, months);
                            p.setProjectEndYear(cal.get(Calendar.YEAR) + "");
                            p.setProjectEndMonth(cal.get(Calendar.MONTH) + "");
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 读取project_entity_new表中glbm字段（例：‘aaaa/bbbb’，则取aaaa），与base_zzjg中的text字段做完全匹配，
     * 若相等，则验证通过，aaaa为该项目的大单位名称
     * @param p
     * @param upperUnits
     */
    public void formatUpperUnit(ProjectEntityNew p, List<BaseUpperUnit> upperUnits) {
        if (CollectionUtil.isNotEmpty(upperUnits)&&!StrUtil.isBlank(p.getGlbm())) {
            String unitName = StrUtil.subBefore(p.getGlbm(), "/", true);
            BaseUpperUnit baseUpperUnit = upperUnits.stream().filter(u -> {
                if (!StrUtil.isEmpty(unitName)) {
                    return u.getUnitName().contains(unitName);
                }
                return false;
            }).findFirst().orElse(null);
            if (!Objects.isNull(baseUpperUnit)) {
                p.setUpperUnit(baseUpperUnit.getUnitCode());
            }
        }
    }

    public void formatStatus(ProjectEntityNew p) {
        // 既有开始日期也有结束日期，则状态为3
        if (!Objects.isNull(p.getProjectStartYear())&&!Objects.isNull(p.getProjectEndYear())) {
            p.setStatus("3");
        }
        // 有开始日期没有结束日期，则状态为2
        if (!Objects.isNull(p.getProjectStartYear())&&Objects.isNull(p.getProjectEndYear())) {
            p.setStatus("2");
        }
        // 没有开始日期也没有结束日期，则状态为1
        if (Objects.isNull(p.getProjectStartYear())&&Objects.isNull(p.getProjectEndYear())) {
            p.setStatus("1");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void formatData() {
        List<ProjectEntityNew> projectEntityNewList = projectEntityNewDao.findAll();
        List<BaseUpperUnit> upperUnits = baseUpperUnitMapper.selectAll();
        projectEntityNewList.stream().forEach(p -> {
            // 格式化项目区间数据
            formatRange(p);
            // 格式化大单位数据
            formatUpperUnit(p, upperUnits);
            // 格式化状态数据
            formatStatus(p);
            projectEntityNewDao.updateByPrimaryKey(p);
        });

    }
}
